package controller;

import model.User;
import model.UserDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的编码格式为UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 打印接收到的用户名和密码
        System.out.println("Received username: " + username);
        System.out.println("Received password: " + password);

        UserDAO userDAO = new UserDAO();
        User user = userDAO.getUserByName(username);

        if (user != null) {
            // 打印从数据库中获取的用户信息
            System.out.println("Database user: " + user.getName());
            System.out.println("Database password: " + user.getPassword());

            if (user.getPassword().equals(password)) {
                request.getSession().setAttribute("user", user);
                response.setStatus(200);
                response.getWriter().write("登录成功");
            } else {
//                403 拒接访问  401 身份验证失败
                response.setStatus(401);
                response.getWriter().write("登录失败，请检查用户名和密码");
            }
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("登录失败，请检查用户名和密码");
        }
    }
}
